package org.flower.web.servlet;

import com.jspsmart.upload.*;
import org.apache.ibatis.session.SqlSession;
import org.flower.bean.CommodityClass;
import org.flower.dao.CommodityClassDao;
import org.flower.dao.impl.CommodityClassDaoImpl;
import org.flower.mapper.CommodityClassMapper;
import org.flower.utils.MyBatisUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

/**
 * 添加商品类servlet
 *
 * @author Aizen
 * @date 2021/12/22
 */
@WebServlet("/manager/addCommodityClassServlet.shtml")
public class AddCommodityClassServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //查询所有分类放到页面的作用域中
        SqlSession sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
        CommodityClassMapper classMapper = sqlSessionFactory.getMapper(CommodityClassMapper.class);
        List<CommodityClass> classList = classMapper.selectByExample(null);
        request.setAttribute("classList",classList);
        sqlSessionFactory.close();
        request.getRequestDispatcher("addCommodityClass.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CommodityClassDao classDao = new CommodityClassDaoImpl();

        //1.实例化对象
        SmartUpload smart = new SmartUpload();
        //2.设置编码
        smart.setCharset("utf-8");
        //3.初始化
        smart.initialize(this,request,response);
        //4.上传文件
        try {
            smart.upload();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        //5.获取专用request对象
        Request req = smart.getRequest();
        String className = req.getParameter("className");
        String pId = req.getParameter("pId");
        int typeById = classDao.getTypeById(Integer.parseInt(pId));

        String classHref = req.getParameter("classHref");


        org.flower.entity.CommodityClass c = new org.flower.entity.CommodityClass();
        c.setImage("");
        c.setType(typeById+1);

        Files files = smart.getFiles();

        String fileName = "";
        File file = files.getFile(0);
        if(!file.isMissing()){
            fileName = file.getFileName();
            try {
                file.saveAs("image/indexImg/"+fileName);
            } catch (SmartUploadException e) {
                e.printStackTrace();
            }
            c.setImage("image/indexImg/"+fileName);
        }

        c.setName(className);
        c.setPid(Integer.parseInt(pId));
        c.setAhref(classHref);

        boolean b = classDao.addCommodityClass(c);

        if(b){
            response.sendRedirect("commodityClassServlet");
        }else{
            response.sendRedirect("addCommodityClassServlet.shtml");
        }


    }
}
